import { nextTick } from "vue";
import { useCrudForm } from "@/composables/useCrudForm";
import { renewFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrRenewRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysHrRenewRequestBill,
  ISysHrRenewRequestBillVm,
  IContractFileParam,
} from "../api/interface";

/**
 * 合同续签申请单信息专用 Composable
 */
export function useRenewInfo() {
  // 创建API实例
  const api = SysHrRenewRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    groupId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    personId: async () => {
      // 返回空数组，人员选择通过自动补全搜索实现
      return [];
    },
    personContractId: async () => {
      // 调用原合同列表接口
      const result = await api.getSysPersonContracts();

      // 转换为useCrudForm期望的格式
      // 优先显示Text，如果没有就显示Value，表单提交传Value
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text || item.Value,
      }));
    },
  };

  /**
   * 搜索员工（自动补全用）
   */
  const searchEmployees = async (query: string) => {
    // 判断输入的是工号还是姓名
    // 如果输入的是纯数字，则按工号搜索；否则按姓名搜索
    const isStaffNo = /^\d+$/.test(query.trim());

    // 根据输入类型构建搜索参数
    const searchParams: any = {
      PageIndex: 1,
      State: '在职' // 只搜索在职员工
    };

    // 根据输入类型设置搜索字段
    if (isStaffNo) {
      searchParams.StaffNo = query;
    } else {
      searchParams.Name = query;
    }

    // 使用新的员工搜索API
    const response = await api.searchPersons(searchParams);

    // 检查响应是否成功
    if (response.Code !== 200 || !response.Data) {
      console.warn('员工搜索API返回异常:', response.Msg || '未知错误');
      return [];
    }

    // 转换为自动补全组件期望的格式
    return response.Data.map((person: any) => ({
      value: person.ID,
      text: person.Name,
      subtitle: `工号: ${person.StaffNo}${person.GroupName ? ` | ${person.GroupName}` : ''}`, // 显示工号和部门作为副标题
      // 扩展数据，包含公司和部门信息
      extData: {
        staffNo: person.StaffNo,
        orgId: person.OrgId || person.Org?.ID,
        orgName: person.OrgName || person.Org?.Name,
        groupId: person.GroupId || person.Group?.ID,
        groupName: person.GroupName || person.Group?.GroupName,
      }
    }));
  };

  // 为personId字段配置searchApi
  if (renewFormConfig.personId) {
    renewFormConfig.personId.searchApi = searchEmployees;
  }

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrRenewRequestBill, ISysHrRenewRequestBillVm>(
    renewFormConfig,
    apiConfig,
    optionLoaders
  );

  // 初始化新字段的默认值
  if (!crudForm.formData.orgId) {
    crudForm.formData.orgId = "";
  }
  if (!crudForm.formData.orgName) {
    crudForm.formData.orgName = "";
  }
  if (!crudForm.formData.groupId) {
    crudForm.formData.groupId = "";
  }
  if (!crudForm.formData.groupName) {
    crudForm.formData.groupName = "";
  }

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysHrRenewRequestBillVm => {
    return {
      Entity: {
        PersonId: crudForm.pickerValues.personId || null,
        StaffNo: crudForm.formData.staffNo || null,
        Name: crudForm.formData.name || null,
        PersonContractId: crudForm.pickerValues.personContractId || null,
        EmploymentType: crudForm.pickerValues.employmentType || null,
        ContractType: crudForm.pickerValues.contractType || null,
        ContractNo: crudForm.formData.contractNo || null,
        SignDate: crudForm.formData.signDate ? new Date(crudForm.formData.signDate) : null,
        ExpireDate: crudForm.formData.expireDate ? new Date(crudForm.formData.expireDate) : null,
        ContractFiles: null,
        Approver: null,
        ApprovalTime: null,
        // 公司ID和部门ID信息
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || null,
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || null,
        BillCode: crudForm.formData.billCode || null,
        // BillStatus和WorkflowStatus不传值，由系统自动设置
        BillStatus: null,
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
      },
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
      SelectedContractFilesIds: extractFileParams(crudForm.formData.contractFiles) || null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysHrRenewRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        ID: originalData.ID || null,
        PersonId: crudForm.pickerValues.personId || originalData.PersonId,
        StaffNo: crudForm.formData.staffNo || originalData.StaffNo,
        Name: crudForm.formData.name || originalData.Name,
        PersonContractId: crudForm.pickerValues.personContractId || originalData.PersonContractId,
        EmploymentType: crudForm.pickerValues.employmentType || originalData.EmploymentType,
        ContractType: crudForm.pickerValues.contractType || originalData.ContractType,
        ContractNo: crudForm.formData.contractNo || originalData.ContractNo,
        SignDate: crudForm.formData.signDate ? new Date(crudForm.formData.signDate) : originalData.SignDate,
        ExpireDate: crudForm.formData.expireDate ? new Date(crudForm.formData.expireDate) : originalData.ExpireDate,
        ContractFiles: null,
        Approver: originalData.Approver,
        ApprovalTime: originalData.ApprovalTime,
        // 公司ID和部门ID信息
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || originalData.OrgId,
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || originalData.GroupId,
        BillCode: crudForm.formData.billCode || originalData.BillCode,
        // BillStatus和WorkflowStatus不传值，由系统自动设置
        BillStatus: '草稿',
        WorkflowStatus: '提交中',
        Remark: crudForm.formData.remark || originalData.Remark,
      },
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
      SelectedContractFilesIds: extractFileParams(crudForm.formData.contractFiles) || null,
    };
  };

  /**
   * 从文件对象数组中提取文件参数（用于SelectedContractFilesIds字段）
   */
  const extractFileParams = (fileData: any): IContractFileParam[] | null => {
    if (!fileData) return null;

    // 如果是数组，提取所有文件的ID并构造参数格式
    if (Array.isArray(fileData) && fileData.length > 0) {
      return fileData.map((file, index) => ({
        FileId: file?.fileID || file?.id,
        Order: index
      })).filter(item => item.FileId); // 过滤掉没有FileId的项
    }

    // 如果是单个文件对象
    if (typeof fileData === 'object' && (fileData?.fileID || fileData?.id)) {
      return [{
        FileId: fileData?.fileID || fileData?.id,
        Order: 0
      }];
    }

    return null;
  };

  // 注意：用工形式和合同类型现在直接使用字符串，不需要数字转换

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",

    // 续签信息
    personId: "PersonId",
    personName: "Name", // 用于详情页显示员工姓名
    staffNo: "StaffNo",
    name: "Name",
    orgId: "OrgId", // 原始的公司ID字段
    orgName: "Org.Name", // 公司名称字段，通过processedData处理
    groupId: "GroupId", // 原始的部门ID字段
    groupName: "Group.GroupName", // 部门名称字段，通过processedData处理
    personContractId: "PersonContract.ContractNo",
    employmentType: "EmploymentType",
    contractType: "ContractType",

    // 合同信息
    contractNo: "ContractNo",
    signDate: "SignDate",
    expireDate: "ExpireDate",

    // 附件信息
    // contractFiles: "ContractFiles", // 注释掉，由ensurePickerFieldsMapping专门处理

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",

    // 备注
    remark: "Remark",
  };

  /**
   * 从API数据填充表单数据
   */
  const populateFormFromApiData = (apiData: ISysHrRenewRequestBill) => {
    // 清空现有数据
    Object.keys(crudForm.formData).forEach(key => {
      crudForm.formData[key] = "";
    });
    Object.keys(crudForm.pickerValues).forEach(key => {
      crudForm.pickerValues[key] = "";
    });

    // 根据字段映射填充数据
    Object.entries(fieldMapping).forEach(([formField, apiField]) => {
      const value = (apiData as any)[apiField];

      if (value !== null && value !== undefined) {
        // 特殊处理日期字段
        if (formField === "signDate" || formField === "expireDate") {
          if (value) {
            const date = new Date(value);
            crudForm.formData[formField] = date.toISOString().split('T')[0];
          }
        }
        // 特殊处理审批时间字段
        else if (formField === "approvalTime") {
          if (value) {
            crudForm.formData[formField] = formatDateTime(value);
          }
        }
        // 特殊处理枚举字段 - 现在API返回字符串，直接使用
        else if (formField === "employmentType") {
          crudForm.formData[formField] = value as string;
          crudForm.pickerValues[formField] = value as string;
        }
        else if (formField === "contractType") {
          crudForm.formData[formField] = value as string;
          crudForm.pickerValues[formField] = value as string;
        }
        // 特殊处理单据状态和工作流状态
        else if (formField === "billStatus") {
          if (value === 0 || value === "草稿") {
            crudForm.formData[formField] = "草稿";
          } else if (value === 1 || value === "正文") {
            crudForm.formData[formField] = "正文";
          } else {
            crudForm.formData[formField] = value;
          }
        }
        // 其他字段直接赋值
        else {
          crudForm.formData[formField] = value;
          // 对于picker类型的字段，同时设置pickerValues
          if (renewFormConfig[formField]?.type === "picker" || renewFormConfig[formField]?.type === "department-picker") {
            crudForm.pickerValues[formField] = value;
          }
        }
      }
    });

    // 处理关联对象数据
    if (apiData.Group) {
      crudForm.formData.group = apiData.Group.GroupName || "";
    }
    if (apiData.PersonContract) {
      crudForm.formData.personContractId = apiData.PersonContract.ContractNo || '';
    }
    // 注意：合同文件的回显逻辑已移到下面的ensurePickerFieldsMapping函数中
  };

  /**
   * 创建合同续签申请单
   */
  const createRenew = async (): Promise<{
    success: boolean;
    data?: ISysHrRenewRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 第一步：调用Add接口保存草稿
    const apiData = convertFormDataToApiFormatForCreate();
    const addResult = await crudForm.create(apiData);

    if (!addResult || !addResult.ID) {
      return {
        success: false,
        validation: validationResult,
        error: "保存草稿失败，请重试"
      };
    }

    // 第二步：调用Edit接口进行提交
    // 设置原始数据为第一步返回的结果，用于Edit接口
    crudForm.originalData.value = addResult;

    // 创建编辑数据格式进行提交
    const editApiData = convertFormDataToApiFormatForEdit();

    const editResult = await crudForm.update(editApiData);

    if (!editResult) {
      return {
        success: false,
        validation: validationResult,
        error: "提交失败，数据已保存为草稿，请稍后重试"
      };
    }

    return {
      success: true,
      data: editResult,
      validation: validationResult
    };
  };

  /**
   * 保存合同续签申请单（编辑）
   */
  const updateRenew = async (): Promise<{
    success: boolean;
    data?: ISysHrRenewRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 加载合同续签申请单详情数据
   */
  const loadRenewDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    // 直接调用API获取完整响应
    const response = await api.get(id);

    if (response && response.Entity) {
      const detail = response.Entity;

      // 设置原始数据
      crudForm.originalData.value = detail;

      // 检查原始数据中的日期字段
      const dateFields = ["ApprovalTime", "SignDate", "ExpireDate"];
      dateFields.forEach(field => {
        if ((detail as any)[field]) {
          console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
        }
      });

      // 先使用通用转换
      crudForm.convertApiDataToFormData(detail, fieldMapping);

      // 添加特殊处理，确保选择器字段正确映射
      await ensurePickerFieldsMapping(detail, response.SelectedContractFilesIds);

      return {
        success: true,
        isMyApprove: response.IsMyApprove || false
      };
    }
    return { success: false };
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any, selectedContractFilesIds?: IContractFileParam[] | null) => {
    // 处理单据编号
    if (apiData.BillCode) {
      crudForm.formData.billCode = apiData.BillCode;
    }

    // 处理单据状态
    if (apiData.BillStatus !== undefined) {
      const statusText = apiData.BillStatus === "草稿" ? "草稿" : "正文";
      crudForm.formData.billStatus = statusText;
      crudForm.pickerValues.billStatus = apiData.BillStatus.toString();
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理用工形式 - 现在API返回字符串，直接使用
    if (apiData.EmploymentType) {
      crudForm.formData.employmentType = apiData.EmploymentType;
      crudForm.pickerValues.employmentType = apiData.EmploymentType;
    }

    // 处理合同类型 - 现在API返回字符串，直接使用
    if (apiData.ContractType) {
      crudForm.formData.contractType = apiData.ContractType;
      crudForm.pickerValues.contractType = apiData.ContractType;
    }

    // 处理部门信息
    if (apiData.Group && renewFormConfig.groupId?.optionsData) {
      const deptOption = renewFormConfig.groupId.optionsData.find(
        (option: any) => option.value === apiData.GroupId
      );
      if (deptOption) {
        crudForm.formData.groupId = deptOption.text;
        crudForm.pickerValues.groupId = apiData.GroupId;
      }
      // 详情页显示部门名称
      crudForm.formData.group = apiData.Group.GroupName || "";
    }

    // 处理员工信息
    console.log("处理员工信息，apiData.Name:", apiData.Name, "apiData.PersonId:", apiData.PersonId);

    // 始终从API数据设置员工姓名，确保有值显示
    if (apiData.Name) {
      // 设置autocomplete组件显示的文本（编辑页显示员工姓名）
      crudForm.formData.personId = apiData.Name;
      // 设置详情页显示的员工姓名
      crudForm.formData.personName = apiData.Name;
      console.log("设置员工姓名显示:", apiData.Name);
    }

    // 设置实际的员工ID用于提交
    if (apiData.PersonId) {
      crudForm.pickerValues.personId = apiData.PersonId;
      console.log("设置员工ID:", apiData.PersonId);
    }

    // 如果有选项数据，也尝试匹配设置
    if (apiData.PersonId && renewFormConfig.personId?.optionsData) {
      const personOption = renewFormConfig.personId.optionsData.find(
        (option: any) => option.value === apiData.PersonId
      );
      if (personOption) {
        crudForm.formData.personId = personOption.text;
        crudForm.pickerValues.personId = apiData.PersonId;
        crudForm.formData.personName = personOption.text;
        console.log("从选项数据匹配设置员工信息:", personOption.text);
      }
    }

    // 处理原员工合同信息
    if (apiData.PersonContractId && renewFormConfig.personContractId?.optionsData) {
      const contractOption = renewFormConfig.personContractId.optionsData.find(
        (option: any) => option.value === apiData.PersonContractId
      );
      if (contractOption) {
        crudForm.formData.personContractId = contractOption.text;
        crudForm.pickerValues.personContractId = contractOption.value;
      }
    } else if (apiData.PersonContract) {
      // 如果没有找到匹配的选项，直接使用PersonContract.ContractNo
      crudForm.formData.personContractId = apiData.PersonContract.ContractNo || '';
      crudForm.pickerValues.personContractId = apiData.PersonContractId || "";
    }

    // 处理合同文件信息 - 优先使用 SelectedContractFilesIds 进行回显
    console.log("处理合同文件回显");
    console.log("selectedContractFilesIds:", selectedContractFilesIds);
    console.log("apiData.ContractFiles:", apiData.ContractFiles, "apiData.ContractFile:", apiData.ContractFile);

    // 优先使用 SelectedContractFilesIds 来构造文件数组
    if (selectedContractFilesIds && selectedContractFilesIds.length > 0) {
      const fileObjects = selectedContractFilesIds
        .sort((a, b) => a.Order - b.Order) // 按Order排序
        .map((fileParam, index) => {
          // 如果只有一个文件且有ContractFile信息，使用详细信息
          const isMainFile = selectedContractFilesIds.length === 1 && apiData.ContractFile;

          return {
            name: isMainFile ? (apiData.ContractFile.FileName || "合同文件") : `合同文件${index + 1}`,
            url: `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileParam.FileId}`,
            extname: isMainFile ? (apiData.ContractFile.FileExt || apiData.ContractFile.Ext || "pdf") : "pdf",
            size: isMainFile ? (apiData.ContractFile.Length || apiData.ContractFile.Size || 0) : 0,
            fileID: fileParam.FileId,
            // uni-file-picker 需要的字段
            tempFilePath: `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileParam.FileId}`,
            path: `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileParam.FileId}`,
            cloudPath: fileParam.FileId,
            // 确保有这些必要字段
            progress: 100,
            status: 'success',
          };
        });

      crudForm.formData.contractFiles = fileObjects;
      console.log("从SelectedContractFilesIds设置文件对象数组:", crudForm.formData.contractFiles);

      // 延迟设置，确保组件已经渲染
      setTimeout(() => {
        console.log("延迟检查文件数据:", crudForm.formData.contractFiles);
        // 强制更新表单值
        const newFormData = { ...crudForm.formData };
        newFormData.contractFiles = fileObjects;
        Object.assign(crudForm.formData, newFormData);
      }, 100);
    }
    // 如果没有 SelectedContractFilesIds，回退到使用 ContractFiles
    else if (apiData.ContractFiles) {
      // 构造文件对象数组格式用于组件显示
      const fileObj = {
        name: apiData.ContractFile?.FileName || "合同文件",
        url: `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${apiData.ContractFiles}`,
        extname: apiData.ContractFile?.FileExt || apiData.ContractFile?.Ext || "pdf",
        size: apiData.ContractFile?.Length || apiData.ContractFile?.Size || 0,
        fileID: apiData.ContractFiles,
        // uni-file-picker 需要的字段
        tempFilePath: `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${apiData.ContractFiles}`,
        path: `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${apiData.ContractFiles}`,
        cloudPath: apiData.ContractFiles,
        // 确保有这些必要字段
        progress: 100,
        status: 'success',
      };

      crudForm.formData.contractFiles = [fileObj];
      console.log("从ContractFiles设置文件对象数组:", crudForm.formData.contractFiles);

      // 延迟设置，确保组件已经渲染
      setTimeout(() => {
        console.log("延迟检查文件数据:", crudForm.formData.contractFiles);
        // 强制更新表单值
        const newFormData = { ...crudForm.formData };
        newFormData.contractFiles = [fileObj];
        Object.assign(crudForm.formData, newFormData);
      }, 100);
    } else {
      console.log("没有合同文件需要回显");
      crudForm.formData.contractFiles = [];
    }

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }
  };

  /**
   * 更新表单配置中的部门数据
   */
  const updateDepartmentData = async () => {
    const commonApiInstance = commonApi();
    const departmentData = await commonApiInstance.GetParentsTree();

    // 更新表单配置中的部门数据
    if (renewFormConfig.groupId && departmentData) {
      renewFormConfig.groupId.departmentData = departmentData;
      // 同时设置optionsData，用于数据映射
      renewFormConfig.groupId.optionsData = departmentData.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));
    }

    return departmentData;
  };

  /**
   * 重写 initializeOptions 方法，同时更新部门数据
   */
  const initializeOptions = async (): Promise<boolean> => {
    // 先调用原始的 initializeOptions
    const result = await crudForm.initializeOptions();

    // 然后更新部门数据
    await updateDepartmentData();

    return result;
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 重写 initializeOptions 方法
    initializeOptions,

    // 合同续签申请单信息专用方法
    createRenew,
    updateRenew,
    loadRenewDetail,
    updateDepartmentData,
    searchEmployees,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,
    populateFormFromApiData,

    // 注意：用工形式和合同类型现在直接使用字符串，不需要枚举转换方法

    // 字段映射
    fieldMapping,
  };
}
